<template>
  <div>
    <a-drawer :width="966" :visible="show" @ok="handleOk" @cancel="handleCancel" unmountOnClose>
      <template #title>
        添加商品
      </template>
      <div flex>
        <div w-660px px-8px v-auto-animate>
          <PickSearchColumn :row-span="12" :columns="columnsSearch" @reset="(val) => {
      init(val);
    }
      " @search="(val) => {
      init(val);
    }
      " />
          <div>
            <div mt-20px>
              <!-- 加载框 -->
              <a-spin :loading="!showGoods">
                <div class="goods-col">
                  <a-row :col-gap="12" :gutter="8">
                    <a-col mt-10px :span="12" v-for="(item, index) in goodsList" @click="handleClickGoods(item)"
                      :key="index">
                      <div px-6px cursor-pointer :class="{ 'checked': item._checked }" flex flex-a-c class="goods-item">
                        <div flex>
                          <div>
                            <a-image
                              :src="item.thumbnail || item.small || 'https://lili-system.oss-cn-beijing.aliyuncs.com/img.png'"
                              width="75"></a-image>
                          </div>
                          <div ml-10px>
                            <div w-150px>
                              <div class="goods-name">{{ item.goodsName }}</div>
                              <div> <a-badge :status="item.marketEnable === 'UPPER' ? 'success' : 'danger'"
                                  :text="item.marketEnable === 'UPPER' ? '售卖中' : '已下架'" /></div>
                            </div>
                            <div>
                              <div>￥{{ unitPrice(item.price) }}</div>
                              <div>{{ item.cost }}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </a-col>

                  </a-row>
                </div>
              </a-spin>

            </div>
          </div>
        </div>
        <div w-306px px-8px class="choose-goods-list">
          <div flex flex-a-c flex-j-sb>
            <div>已选商品</div>
            <div color-gray text-12px cursor-pointer @click="clearAll">全部清除</div>

          </div>

          <a-alert mt-10px v-if="props.max" type="normal">最多选中{{ props.max }}个商品</a-alert>
          <a-alert mt-10px type="normal">滑动商品可变换展示位置</a-alert>
          <div class="checked-goods-list" v-auto-animate>
            <drawGoods :moveCard="moveCard" :id="item.id" :index="index" :key="index"
              v-for="(item, index) in checkedGoods">
              <div flex>
                <div>
                  <a-image
                    :src="item.thumbnail || item.small || 'https://lili-system.oss-cn-beijing.aliyuncs.com/img.png'"
                    width="75"></a-image>
                </div>
                <div ml-10px>
                  <div w-170px>
                    <div class="goods-name">{{ item.goodsName }}</div>
                    <div><a-badge :status="item.marketEnable === 'UPPER' ? 'success' : 'danger'"
                        :text="item.marketEnable === 'UPPER' ? '售卖中' : '已下架'" /></div>
                  </div>
                  <div>
                    <div color-red text-15px font-600>￥{{ unitPrice(item.price) }}</div>
                    <div text-12px color-gray>库存：{{ item.quantity }}</div>
                    <div text-right>
                      <a-button @click="handleClickDelGoods(item, index)" size="mini">删除</a-button>
                    </div>
                  </div>
                </div>
              </div>

            </drawGoods>
          </div>
        </div>
      </div>
      <template #footer>
        <div flex flex-a-c flex-j-sb>
          <div flex flex-a-c flex-justify-end w-660px>
            <a-pagination :total="total" @change="changePagination" show-total />
          </div>
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" @click="handleOk">确定</a-button>
          </a-space>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { SearchRule, } from '@/types/global';
import { goodsType, marketEnable, salesModel, } from '@/utils/tools';
import { PickSearchColumn } from '@pickmall/ui-v3-components';
import { unitPrice } from '@/utils/filters';
import { getGoodsSkuData } from '@/api/goods';
import drawGoods from './draw-goods.vue'
import { Message } from "@arco-design/web-vue";

const props = defineProps({
  templateModel: {
    type: String,
    default: "normal"
  },
  res: {
    type: null
  },
  bind: {
    type: null
  },
  max: {
    type: null,
    default: ''
  },
  model:{
    type: null
  }
})
// const isNormal  = ref<boolean>(props.templateModel === 'normal');

const emit = defineEmits(['callback'])
const params = ref({
  pageNumber: 1, // 当前页数
  pageSize: 12, // 页面大小
  sort: 'createTime', // 默认排序字段
  order: 'desc', // 默认排序方式

})
const checkedGoods = ref<any>([])
const showGoods = ref<boolean>(false)
const goodsList = ref<any>([])
const total = ref<number>(0)
const columnsSearch: Array<SearchRule> = [
  {
    label: '商品名称',
    model: 'goodsName',
    disabled: false,
    input: true,
  },
  {
    label: '店铺名称',
    model: 'storeName',
    disabled: false,
    input: true,
  },
  {
    label: '状态',
    model: 'marketEnable',
    disabled: false,
    select: {
      options: marketEnable,
    },
  },
  {
    label: '销售模式',
    model: 'salesModel',
    disabled: false,
    select: {
      options: salesModel,
    },
  },
  {
    label: '商品类型',
    model: 'goodsType',
    disabled: false,

    select: {
      options: goodsType,
    },
  },
  {
    label: '商品编号',
    model: 'id',
    disabled: false,
    input: true,
  },
];




const show = ref(false);
const open = () => {
  show.value = true
  init();
  checkedGoods.value = props.model || props.res.data[props.bind|| 'list']
}
defineExpose({ open })


const handleOk = () => {
  show.value = false;
  callback();
};
const handleCancel = () => {
  show.value = false;
}
// 删除商品
function handleClickDelGoods(val: any, index: number) {
  // 操作数据后更新视图
  goodsList.value.forEach((item: any) => {
    if (item.id === val.id) {
      item._checked = false
    }
  })
  // console.log(checkedGoods.value)
  if (checkedGoods.value.length) {
    checkedGoods.value.splice(index, 1)
  }
}

// 清除所有选中的商品
function clearAll() {
  goodsList.value.forEach((item: any) => {
    checkedGoods.value.forEach((checked: any) => {
      if (item.id === checked.id) {
        item._checked = false
      }
    })
  })
  checkedGoods.value = []
}

// 选值回调
function callback() {
  emit('callback', checkedGoods.value)
}
// 点击商品
function handleClickGoods(val: any) {
  console.log(props.max, 'props.max')
  if (props.max && (!val._checked && checkedGoods.value.length >= props!.max)) {
    Message.error('最多只能选择' + props.max + '个商品')
    return
  }
  // if(props.max && checkedGoods.value.length >= props.max){
  //   Message.error('最多只能选择'+props.max+'个商品')
  //   return
  // }
  // 切换选中状态
  val._checked = !val._checked;

  // 如果已选商品列表不为空
  if (checkedGoods.value.length) {
    // 检查新商品是否已经存在于已选商品列表中
    const isExist = checkedGoods.value.some((item: any) => item.id === val.id);

    // 如果新商品不存在于已选商品列表中，则将其添加到已选商品列表中
    if (!isExist) {
      checkedGoods.value.push(val);
    }
  } else {
    // 如果已选商品列表为空，则将新商品添加到已选商品列表中
    checkedGoods.value.push(val);
  }

  // 如果新商品被取消选中，则从已选商品列表中移除新商品
  if (!val._checked) {
    checkedGoods.value = checkedGoods.value.filter((item: any) => item.id !== val.id);
  }
}

// 点击分页器
function changePagination(pageNumber: number) {
  params.value.pageNumber = pageNumber
  init()
}

const moveCard = (dragIndex: number, hoverIndex: number) => {
  const item = checkedGoods.value[dragIndex]
  checkedGoods.value.splice(dragIndex, 1)
  checkedGoods.value.splice(hoverIndex, 0, item)
}
// 初始化商品数据
async function init(val?: any) {
  if (val) {
    params.value = {
      ...params.value,
      ...val,
    }
  }

  showGoods.value = false
  const res = await getGoodsSkuData(params.value);
  showGoods.value = true
  if (res.data.success) {
    total.value = res.data.result.total
    const data = res.data.result.records
    if (data.length) {
      // 判断当前是否有选中的值
      if (checkedGoods.value.length) {
        // 如果有选中的值，则遍历选中的值，判断是否存在于当前返回的商品列表中
        checkedGoods.value.forEach((item: any) => {
          // 如果存在，则将当前商品的选中状态改为true
          data.forEach((val: any) => {
            if (item.id === val.id) {
              val._checked = true
            }
          })
        })
        goodsList.value = data
      }
      else {
        goodsList.value = data.map((item: any) => {
          return {
            ...item,
            _checked: false
          }
        })
      }
    }
  }


}

</script>

<style scoped lang="less">
.choose-goods-list {
  border-left: 1px solid var(--color-neutral-3);
}

.checked {
  border: 1px solid rgb(var(--arcoblue-6)) !important;
  background-color: rgb(var(--arcoblue-1)) !important;
}

.goods-item {
  border: 1px solid var(--color-neutral-3);
  height: 100px;
  transition: 0.3s;
}

.goods-col {
  height: calc(100vh - (65px + 48px + 156px + 90px));
}

.goods-name {
  /* 适用于webkit内核和移动端 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.2;
}

.checked-goods-list {
  height: calc(100vh - (65px + 48px + 50px + 40px + 40px + 30px));
  overflow: hidden;
  overflow-y: auto;
}
</style>
